package com.ai.doc.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

/**
 * @author hanyu
 */
@Slf4j
public class EchartsUtil {
    String phantomjsPath;
    String echartsConvertPath;
    String filePath;
    Boolean isLinux;
    Boolean deleteFile;

    public EchartsUtil(String phantomjsPath, String echartsConvertPath, String filePath, Boolean isLinux, Boolean deleteFile) {
        this.phantomjsPath = phantomjsPath;
        this.echartsConvertPath = echartsConvertPath;
        this.filePath = filePath;
        this.isLinux = isLinux;
        this.deleteFile = deleteFile;
    }

    public String generateEchart(int type, String options, int width, int height) {
        switch (type) {
            case 1: {
                return generateEchart1(options, width, height);
            }
            case 2: {
                return generateEchart2(options, width, height);
            }
            case 3: {
                return generateEchart3(options, width, height);
            }
            default: {

            }
        }
        return "";
    }

    public String generateEchart1(String options, int width, int height) {
        if (!isLinux) {
            return "";
        }
        String fileName = "chart-" + UUID.randomUUID().toString().toLowerCase().substring(0, 8) + ".png";
        String imgPath = filePath + fileName;
        File file = FileUtil.file(imgPath);
        Process process = null;

        String cmd = phantomjsPath + " " + echartsConvertPath + " -o " + options + " -t file -f " + imgPath + " -w " + width + " -h " + height;
        String path = filePath + "echartImgCreate.sh";
        File echartImgCreateFile = FileUtil.file(path);
        FileUtil.writeUtf8String(cmd, echartImgCreateFile);

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", "sh " + path);
        pb.redirectErrorStream(true);

        log.info("执行命令：{}", CollUtil.join(pb.command(), " "));
        BufferedReader br = null;
        try {
            process = pb.start();
            br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = br.readLine()) != null) {
                log.info(imgPath + "执行结果：" + line);
            }
            int i = process.waitFor();
            log.info(imgPath + "结果反馈waitFor=" + i);
            int i1 = process.exitValue();
            log.info(imgPath + "结果反馈exitValue=" + i1);
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
            if (process != null) {
                process.destroy();
            }
        }

        String encode = "";
        if (null != file) {
            if(file.exists()) {
                encode = Base64.encode(file);
            }
            if (deleteFile) {
                file.delete();
            }
        }
        return encode;
    }


    public String generateEchart2(String options, int width, int height) {
        String fileName = "chart-" + UUID.randomUUID().toString().toLowerCase().substring(0, 8) + ".png";
        String imgPath = filePath + fileName;
        File file = FileUtil.file(imgPath);
        Process process = null;
        BufferedReader br = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(
                    phantomjsPath, echartsConvertPath, "-o", options, "-t", "file", "-f",
                    imgPath, "-w", width + "", "-h", height + "");

            log.info("执行命令：{}", CollUtil.join(pb.command(), " "));
            pb.redirectErrorStream(true);

            process = pb.start();
            br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = br.readLine()) != null) {
                log.info(imgPath + "执行结果：" + line);
            }
            int i = process.waitFor();
            log.info(imgPath + "结果反馈waitFor=" + i);
            int i1 = process.exitValue();
            log.info(imgPath + "结果反馈exitValue=" + i1);

        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
            if (process != null) {
                process.destroy();
            }

        }

        String encode = "";
        if (null != file) {
            if(file.exists()) {
                encode = Base64.encode(file);
            }
            if (deleteFile) {
                file.delete();
            }
        }
        return encode;
    }

    public String generateEchart3(String options, int width, int height) {
        String fileName = "chart3-" + UUID.randomUUID().toString().toLowerCase().substring(0, 8) + ".png";
        String imgPath = filePath + fileName;
        File file = FileUtil.file(imgPath);
        Process process = null;
        try {
            String cmd = phantomjsPath + " " + echartsConvertPath + " -o " + options + " -t file -f " + imgPath + " -w " + width + " -h " + height;
            log.info("执行命令：" + cmd);
            process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = br.readLine()) != null) {
                log.info(imgPath + "执行结果：" + line);
            }
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            if (process != null) {
                try {
                    process.getOutputStream().close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
                process.destroy();
            }

        }

        String encode = "";
        if (null != file) {
            if(file.exists()) {
                encode = Base64.encode(file);
            }
            if (deleteFile) {
                file.delete();
            }
        }
        return encode;
    }
}
